package com.jilujia.web.controller;

import java.io.File;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import com.jilujia.web.json.ImageData;

@Controller
public class ImageController extends AbstractWebController {

	private static final Logger LOG = LoggerFactory.getLogger(ImageController.class);

	@Autowired
	private WebApplicationContext webApplicationContext;

	public ImageController() {
	}

	@RequestMapping(value = "/image/upload", method = RequestMethod.POST)
	@Secured( { "ROLE_USER" })
	public @ResponseBody
	ImageData uploadImage(@RequestParam String dir, Principal currentUser, HttpServletRequest request)
			throws FileUploadException {

		String savePath = webApplicationContext.getServletContext().getRealPath("/") + "attached/";
		LOG.debug("savePath:{}", savePath);
		String saveUrl = request.getContextPath() + "/attached/";
		LOG.debug("saveUrl:{}", saveUrl);

		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

		long maxSize = 1000000;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return getError("is Not MultipartContent");
		}

		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			return getError("not a dir");
		}

		if (!uploadDir.canWrite()) {
			return getError("can not write");
		}

		String dirName = request.getParameter("dir");
		if (dirName == null) {
			dirName = "image";
		}
		if (!extMap.containsKey(dirName)) {
			return getError("1");
		}

		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List items = upload.parseRequest(request);
		Iterator itr = items.iterator();
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			String fileName = item.getName();
			// long fileSize = item.getSize();
			if (!item.isFormField()) {
				if (item.getSize() > maxSize) {
					return getError("2");
				}
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
					return getError("" + extMap.get(dirName) + "");
				}

				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
				try {
					File uploadedFile = new File(savePath, newFileName);
					item.write(uploadedFile);
				} catch (Exception e) {
					return getError("3");
				}

				ImageData imageData = new ImageData();
				imageData.setError(0);
				String url = saveUrl + newFileName;

				LOG.debug("url:{}", url);
				imageData.setUrl(url);
				return imageData;
			}
		}

		return getError("end");
	}

	private ImageData getError(String message) {
		ImageData imageData = new ImageData();
		imageData.setError(1);
		imageData.setMessage(message);
		return imageData;
	}

}
